package com.example.test06thread.readWriteLock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author: fxy
 * @Date: 2022/05/27/16:28
 * @Description:
 */
public class ReadWriteLockTest {
    public static void main(String[] args) {
        MyCacheLock myCache = new MyCacheLock();
        //写操作线程
        for (int i=1;i<=6;i++){
            final String temp=i+"";
            new Thread(()->{
                myCache.put(temp,Thread.currentThread().getName());
            },String.valueOf(i)).start();
        }
        //读操作线程
        for (int i=1;i<=10;i++){
            final String temp=i+"";
            new Thread(()->{
                myCache.get(temp);
            },String.valueOf(i)).start();
        }
    }
}

/**
 * 加锁
 */
class MyCacheLock{
    private volatile Map<String,Object> map = new HashMap<>();
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    //加锁存，写
    public void put(String key,Object value){
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"写入"+key);
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"写入结束！");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }

    }
    //取，读
    public Object get(String key) {
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "读取" + key);
            Object o = map.get(key);
            System.out.println(Thread.currentThread().getName() + "读取结束！");
            return o;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }
        return null;
    }
}


/**
 * 普通自定义未加锁
 * 读写有些乱，在多线程环境下
 */
class MyCache{
    private volatile Map<String,Object> map = new HashMap<>();

    //存，写
    public void put(String key,Object value){
        System.out.println(Thread.currentThread().getName()+"写入"+key);
        map.put(key,value);
        System.out.println(Thread.currentThread().getName()+"写入结束！");
    }
    //取，读
    public Object get(String key){
        System.out.println(Thread.currentThread().getName()+"读取"+key);
        Object o = map.get(key);
        System.out.println(Thread.currentThread().getName()+"读取结束！");
        return o;
    }
}
